package com.em.service.impl;

import com.em.dto.UserDTO;
import com.em.entity.User;
import com.em.mapper.UserMapper;
import com.em.service.UserService;
import com.em.utils.page.PageResult;
import com.em.utils.page.Result;
import com.em.vo.UserVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author exclusive
 * @version 1.0
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;


    /**
     * 新增用户
     *
     * @param user 用户
     */
    @Override
    public Result<?> addUser(User user) {
        log.info("新增用户 {}", user);

        Result<?> result = new Result<>();
        int count = userMapper.findByName(user.getName());
        if (count > 0) {
            result.setCode("500");
            result.setMsg("用户名已存在");
            return result;
        }

        userMapper.addUser(user);
        result.setCode("200");
        result.setMsg("执行成功");
        return result;
    }

    /**
     * 查询用户列表
     *
     * @return 返回用户数据
     */
    @Override
    public Result<PageResult> getUserList(UserDTO dto) {
        log.info("查询用户列表 {}", dto);

        Result<PageResult> result = new Result<>();
        PageHelper.startPage(Integer.parseInt(dto.getPage()), Integer.parseInt(dto.getPageSize()));
        Page<UserVO> userPage = userMapper.getUserList();
        result.setCode("200");
        result.setMsg("执行成功");
        result.setData(new PageResult(userPage.getTotal(), userPage.getResult()));
        return result;
    }
}
